import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  message,
  Row,
  Col,
  Table,
  Tag,
  Space,
  Typography,
  Alert,
  Statistic,
  Progress,
  Modal,
  Tabs,
  Switch,
  Divider,
  Timeline,
  Badge,
  Tooltip
} from 'antd';
import {
  MonitorOutlined,
  WarningOutlined,
  SettingOutlined,
  HistoryOutlined,
  BellOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  EyeOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;

const StrategyMonitor = () => {
  const [strategies, setStrategies] = useState([
    {
      id: 1,
      name: '价值成长混合策略',
      status: 'normal',
      realtimeReturn: 0.5,
      maxDrawdown: -4.2,
      volatility: 12.8,
      sharpeRatio: 1.45,
      alerts: []
    },
    {
      id: 2,
      name: '量化择时策略',
      status: 'warning',
      realtimeReturn: -1.8,
      maxDrawdown: -9.5,
      volatility: 15.2,
      sharpeRatio: 1.23,
      alerts: [
        { level: 'warning', message: '日收益率低于-1.5%' }
      ]
    },
    {
      id: 3,
      name: '低风险稳健策略',
      status: 'danger',
      realtimeReturn: -2.5,
      maxDrawdown: -10.8,
      volatility: 6.8,
      sharpeRatio: 1.67,
      alerts: [
        { level: 'danger', message: '最大回撤超过10%' },
        { level: 'warning', message: '持仓偏离度超过5%' }
      ]
    }
  ]);

  const [alerts, setAlerts] = useState([
    { id: 1, time: '2024-01-20 14:30', strategy: '低风险稳健策略', level: 'danger', message: '最大回撤超过10%', status: 'pending' },
    { id: 2, time: '2024-01-20 14:25', strategy: '低风险稳健策略', level: 'warning', message: '持仓偏离度超过5%', status: 'pending' },
    { id: 3, time: '2024-01-20 14:15', strategy: '量化择时策略', level: 'warning', message: '日收益率低于-1.5%', status: 'processed' },
  ]);

  const [isSettingModalVisible, setIsSettingModalVisible] = useState(false);
  const [selectedStrategy, setSelectedStrategy] = useState(null);
  const [form] = Form.useForm();
  
  const handleOpenSettings = (record) => {
    setSelectedStrategy(record);
    form.setFieldsValue(record);
    setIsSettingModalVisible(true);
  };

  const handleSaveSettings = async () => {
    try {
      await form.validateFields();
      message.success('预警规则已保存！');
      setIsSettingModalVisible(false);
    } catch (error) {
      console.error('保存失败:', error);
    }
  };
  
  const getStatusTag = (status) => {
    if (status === 'normal') return <Tag color="success">正常</Tag>;
    if (status === 'warning') return <Tag color="warning">警告</Tag>;
    if (status === 'danger') return <Tag color="error">危险</Tag>;
    return <Tag>{status}</Tag>;
  };
  
  const monitorColumns = [
    { title: '策略名称', dataIndex: 'name', key: 'name', width: 200 },
    { title: '状态', dataIndex: 'status', key: 'status', width: 100, render: getStatusTag },
    { title: '实时收益率(%)', dataIndex: 'realtimeReturn', key: 'realtimeReturn', width: 150, render: (v) => <Statistic value={v} precision={2} valueStyle={{ fontSize: 14, color: v >= 0 ? '#52c41a' : '#ff4d4f' }} /> },
    { title: '最大回撤(%)', dataIndex: 'maxDrawdown', key: 'maxDrawdown', width: 150, render: (v) => <Statistic value={v} precision={2} valueStyle={{ fontSize: 14, color: '#ff4d4f' }} /> },
    { title: '夏普比率', dataIndex: 'sharpeRatio', key: 'sharpeRatio', width: 120, render: (v) => <Statistic value={v} precision={2} valueStyle={{ fontSize: 14 }} /> },
    { title: '预警数量', dataIndex: 'alerts', key: 'alerts', width: 120, render: (alerts) => <Badge count={alerts.length} /> },
    { title: '操作', key: 'action', width: 180, render: (_, record) => (
        <Space>
          <Button icon={<SettingOutlined />} onClick={() => handleOpenSettings(record)}>规则设置</Button>
          <Button icon={<EyeOutlined />}>详情</Button>
        </Space>
      )
    }
  ];
  
  const alertColumns = [
    { title: '时间', dataIndex: 'time', key: 'time', width: 180 },
    { title: '策略名称', dataIndex: 'strategy', key: 'strategy', width: 200 },
    { title: '等级', dataIndex: 'level', key: 'level', width: 100, render: (l) => <Tag color={l === 'danger' ? 'error' : 'warning'}>{l === 'danger' ? '危险' : '警告'}</Tag> },
    { title: '预警信息', dataIndex: 'message', key: 'message' },
    { title: '状态', dataIndex: 'status', key: 'status', width: 100, render: (s) => <Tag color={s === 'pending' ? 'processing' : 'success'}>{s === 'pending' ? '待处理' : '已处理'}</Tag> },
    { title: '操作', key: 'action', width: 120, render: (_, record) => (
      <Button 
        type="link" 
        onClick={() => setAlerts(alerts.map(a => a.id === record.id ? {...a, status: 'processed'} : a))}
        disabled={record.status === 'processed'}
      >
        标记为已处理
      </Button>
    )}
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>策略监控</Title>
      <Paragraph type="secondary">实时监控策略运行状态，及时发现和处理风险</Paragraph>
      <Tabs defaultActiveKey="1">
        <TabPane tab={<span><MonitorOutlined />监控仪表盘</span>} key="1">
          <Table dataSource={strategies} columns={monitorColumns} rowKey="id" pagination={false} />
        </TabPane>
        <TabPane tab={<span><BellOutlined />预警中心 <Badge count={alerts.filter(a => a.status === 'pending').length} /></span>} key="2">
          <Table dataSource={alerts} columns={alertColumns} rowKey="id" />
        </TabPane>
        <TabPane tab={<span><HistoryOutlined />操作日志</span>} key="3">
          <Timeline>
            <Timeline.Item color="green">2024-01-20 15:00 - 用户 "admin" 标记预警 #3 为已处理</Timeline.Item>
            <Timeline.Item color="red">2024-01-20 14:30 - 系统触发 "低风险稳健策略" 的 "最大回撤超过10%" 预警</Timeline.Item>
            <Timeline.Item color="orange">2024-01-20 14:15 - 系统触发 "量化择时策略" 的 "日收益率低于-1.5%" 预警</Timeline.Item>
            <Timeline.Item color="blue">2024-01-20 10:00 - 用户 "admin" 更新 "低风险稳健策略" 的预警规则</Timeline.Item>
          </Timeline>
        </TabPane>
      </Tabs>
      <Modal
        title="预警规则设置"
        open={isSettingModalVisible}
        onOk={handleSaveSettings}
        onCancel={() => setIsSettingModalVisible(false)}
        width={600}
        okText="保存规则"
      >
        {selectedStrategy && (
          <Form form={form} layout="vertical">
            <Title level={5}>策略: {selectedStrategy.name}</Title>
            <Form.Item label="日收益率预警 (%)">
              <InputNumber placeholder="例如: -2" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="最大回撤预警 (%)">
              <InputNumber placeholder="例如: 10" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="持仓偏离度预警 (%)">
              <InputNumber placeholder="例如: 5" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="通知方式">
              <Select mode="multiple" placeholder="选择通知方式">
                <Option value="site">站内信</Option>
                <Option value="email">邮件</Option>
                <Option value="sms">短信</Option>
              </Select>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default StrategyMonitor; 